package com.wang.bootbuilder.handler;

import com.wang.bootbuilder.execption.CaptchaException;
import com.wang.bootbuilder.execption.CustomizeException;
import com.wang.bootbuilder.execption.NotHasPermissionException;
import com.wang.bootbuilder.tools.JsonResult;
import com.wang.bootbuilder.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/*
全局异常处理
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    /*
    默认异常处理
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public JsonResult error(Exception e) {
        e.printStackTrace();
        return JsonResult.error().message("服务器出现异常，请稍后再试");
    }

    /*
    特定异常处理
     */
    @ResponseBody
    @ExceptionHandler(CustomizeException.class)
    public JsonResult error(CustomizeException e) {
        e.printStackTrace();
        return JsonResult.error().message(e.getMsg());
    }

    /*
    处理权限异常
     */
    @ResponseBody
    @ExceptionHandler(NotHasPermissionException.class)
    public JsonResult error(NotHasPermissionException e) {
        e.printStackTrace();
        return JsonResult.error().status(e.getCode()).message(e.getMsg());
    }

    /*
    处理验证码异常
     */
    @ResponseBody
    @ExceptionHandler(CaptchaException.class)
    public JsonResult error(CaptchaException e) {
        e.printStackTrace();
        return JsonResult.error().status(e.getCode()).message(e.getMsg());
    }

    /*
    处理@Validated参数校验失败异常
     */
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult error(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        String returnStr = StringUtils.EMPTY;
        if (result.hasErrors()) {
            List<ObjectError> errors = result.getAllErrors();
            List<String> errorMessageList = new ArrayList<>();
            if (errors != null) {
                errors.forEach(p -> {
                    FieldError fieldError = (FieldError) p;
                    log.warn("Bad Request Parameters: dto entity [{}],field [{}],message [{}]",fieldError.getObjectName(), fieldError.getField(), fieldError.getDefaultMessage());
                    errorMessageList.add(fieldError.getDefaultMessage());
                });
                returnStr = StringUtils.join(errorMessageList, "/");
            }
        }
        return JsonResult.error().message(returnStr);
    }

}
